import utils from './utils'
import config from './config.js'
import wxJsdk from './wxJsdk.js'

function getAppId(){
    let appid = utils.getQueryString('appid')
    if(!appid){
        appid = utils.getSession('appid')
    }else {
        utils.setSession('appid',appid)
		config.appid = appid
    }
    return appid
}

function getLesseeId(){
    let lesseeid = utils.getQueryString("lesseeid")
    if(!lesseeid){
        lesseeid = utils.getSession('lesseeid')
    }else {
        utils.setSession('lesseeid',lesseeid)
		config.lesseeid = lesseeid
    }
    return lesseeid
}

function loginAction(call){
	let appid = getAppId()
	let lesseeid = getLesseeId()
	let user = utils.getSession('user')
	let token = utils.getSession('token')
	let fromPush = utils.getQueryString("fromPush")
	
	if(fromPush == "OPEN_API"){
	    return
	}
	if(user && token){
		config.user = user;
		config.token = token;
		if(call){
			call()
		}
		return
	}
	if(appid && lesseeid){
	    let redirectUri = encodeURIComponent(location.origin + location.pathname + location.search + "#/pages/login/index")
		let state =  window.btoa(location.hash)
		let pages = getCurrentPages();
		if(pages.length>1){
			uni.navigateBack({
				complete(){
					setTimeout(()=>{
						location.replace("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + redirectUri + "&response_type=code&scope=snsapi_base&state=" + state + "#wechat_redirect") 
					},100)
				}
			})
		}else{
			location.replace("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + redirectUri + "&response_type=code&scope=snsapi_base&state=" + state + "#wechat_redirect") 
		}
	}else{
		if(!appid){
			alert('请维护APPID')
		}else{
			alert('请维护企业号')
		}
	}
}

export default{
    loginAction
}
